package com.imooc.festec.latte_core.app;


import android.graphics.Bitmap;

import com.joanzapata.iconify.IconFontDescriptor;
import com.joanzapata.iconify.Iconify;

import java.util.ArrayList;
import java.util.WeakHashMap;

/*
 * 配置文件
 * */
public class Configurator {
	
	//  static 声明的需要全大写常量
	private static final WeakHashMap<String, Object> LATTE_CONFIGS = new WeakHashMap<>();
	
	private static final ArrayList<IconFontDescriptor> ICONS = new ArrayList<>();
	
	
	private Configurator() {
		LATTE_CONFIGS.put(ConfigType.CONFIG_READY.name(), false);
	}
	
	// 单例: 线程安全的懒汉模式的单利， 使用静态内部类
	public static Configurator getInstance() {
		return Holder.INSTANCE;
	}
	
	final WeakHashMap<String, Object> getLatteConfigs() {
		return LATTE_CONFIGS;
	}
	
	//使用静态内部类
	private static class Holder {
		private static final Configurator INSTANCE = new Configurator();
	}
	
	public final void configure() {
		this.initIcons();
		LATTE_CONFIGS.put(ConfigType.CONFIG_READY.name(), true);
	}
	
	public final Configurator withApiHost(String host) {
		LATTE_CONFIGS.put(ConfigType.API_HOST.name(), host);
		return this;
	}
	
	public final Configurator withIcon(IconFontDescriptor descriptor) {
		ICONS.add(descriptor);
		return this;
	}
	
	
	private void checkConfiguration() {
		final boolean isReady = (boolean) LATTE_CONFIGS.get(ConfigType.CONFIG_READY.name());
		
		if (!isReady) {
			throw new RuntimeException("Configuration is not ready, call configure");
		}
	}
	
	private void initIcons() {
		if (ICONS.size() > 0) {
			final Iconify.IconifyInitializer initializer = Iconify.with(ICONS.get(0));
			
			for (int i = 0; i < ICONS.size(); i++) {
				initializer.with(ICONS.get(i));
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	final <T> T getConfiguration(Enum<ConfigType> key) {
		this.checkConfiguration();
		return (T) LATTE_CONFIGS.get(key);
	}
}
